package com.tanhua.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.model.dto.UserFreeze;
import com.tanhua.admin.service.ManagerService;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class ManagerServiceImpl implements ManagerService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 后台查询所有用户信息
     */
    @Override
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        //1.调用api查询数据列表
        Page<UserInfo> infopage = userInfoApi.findAllUsers(page, pagesize);
        //2.将Page对向转化为PageResult
        PageResult result = new PageResult(page, pagesize,
                infopage.getTotal(), infopage.getRecords());
        //3.构建返回值
        return result;
    }


    /**
     * 查询单个用户详情
     */
    @Override
    public UserInfo findById(Long id) {
        UserInfo info = userInfoApi.findById(id);
        //如果redis当中存在冻结缓存,说明该用户被冻结
        if (redisTemplate.hasKey(Constants.FREEZE_USER + info.getId())) {
            info.setUserStatus("2");
        }
        return info;
    }

    /**
     * 根据用户id查询视频
     *
     * @return
     */
    @Override
    public PageResult findVideos(Integer page, Integer pagesize, Long uid) {
        //调用videoApi
        return videoApi.findByUserId(page, pagesize, uid);
    }

    //查询动态列表
    @Override
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        //1.调用Api查询数据:Movement对象
        PageResult result = movementApi.findByUserIdList(page, pagesize, uid, state);

        //解析PageResult,获取Movement对象列表
        List<Movement> items = (List<Movement>) result.getItems();
        //3.有个Movement对象转化一个vo
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        //获取ids
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        //Api查询ids的详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);

        //stream流封装vo
        List<MovementsVo> collect = items.parallelStream()
                .filter(movement ->
                        map.get(movement.getUserId()) != null)
                .map(movement -> {
                    return MovementsVo.init(map.get(movement.getUserId()), movement);
                }).collect(Collectors.toList());

        //构造返回值
        PageResult res = new PageResult();
        res.setItems(collect);
        return res;
    }

    //冻结用户
    @Override
    public Map userFreeze(UserFreeze freeze) {
        //获取信息
        Integer time = freeze.getFreezingTime();
        Long userId = Long.valueOf(freeze.getUserId());
        //判断时间范围
        int days = 0;
        if (time == 1) {
            days = 3;
        } else if (time == 2) {
            days = 7;
        } else if (time == 3) {
            days = -1;
        }
        String value = JSON.toJSONString(freeze);
        //缓存设置冻结时间
        if (days > 0) {
            redisTemplate.opsForValue().set(Constants.FREEZE_USER + userId, value, days, TimeUnit.DAYS);
        } else {
            redisTemplate.opsForValue().set(Constants.FREEZE_USER + userId, value);
        }

        Map map = new HashMap();
        map.put("message", "冻结成功!");
        return map;
    }


    //解冻用户
    @Override
    public Map userUnfreeze(UserFreeze freeze) {
        //获取信息:需要取消冻结的用户id
        Long userId = Long.valueOf(freeze.getUserId());
        //删除redis数据
        redisTemplate.delete(Constants.FREEZE_USER + userId);
        Map map = new HashMap();
        map.put("message", "解冻成功!");
        return map;
    }
}
